package com.medical.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.medical.service.AlipayService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

@RestController
@RequestMapping("/alipay")
@Slf4j
public class PaymentController {

    @Autowired
    private AlipayService alipayService;

    @PostMapping("/create")
    public String createOrder(@RequestBody Map<String, String> params) {
        try {
            String orderNo = params.get("orderNo");
            if (StringUtils.isEmpty(orderNo)) {
                orderNo = generateOrderNo(); // 生成订单号
            }
            String totalAmount = params.get("totalAmount");
            String subject = params.get("subject");

            return alipayService.createOrder(orderNo, totalAmount, subject);
        } catch (Exception e) {
            log.error("创建支付订单失败", e);
            throw new RuntimeException("创建支付订单失败", e);
        }
    }

    private String generateOrderNo() {
        return "ORDER" + System.currentTimeMillis() + new Random().nextInt(1000);
    }

    @PostMapping("/notify")
    public String notify(HttpServletRequest request) throws AlipayApiException {
        Map<String, String> params = new HashMap<>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (String name : requestParams.keySet()) {
            String[] values = requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            params.put(name, valueStr);
        }

        log.info("支付宝异步通知，参数：{}", params);

        if (alipayService.verifyNotify(params)) {
            String tradeStatus = params.get("trade_status");
            if ("TRADE_SUCCESS".equals(tradeStatus) || "TRADE_FINISHED".equals(tradeStatus)) {
                String orderNo = params.get("out_trade_no");
                log.info("订单{}支付成功", orderNo);
                return "success";
            }
        } else {
            log.error("支付宝异步通知验签失败");
        }
        return "failure";
    }

    // 注入配置值
    @Value("${alipay.alipay-public-key}")
    private String alipayPublicKey;

    @Value("${alipay.charset:UTF-8}")
    private String charset;

    @Value("${alipay.sign-type:RSA2}")
    private String signType;

    @GetMapping("/return")
    public void alipayReturn(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Map<String, String> params = new HashMap<>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (String name : requestParams.keySet()) {
            String[] values = requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            params.put(name, valueStr);
        }

        try {
            // 验证签名
            boolean signVerified = AlipaySignature.rsaCheckV1(params, alipayPublicKey, charset, signType);

            // 获取支付宝返回的参数
            String orderNo = params.get("out_trade_no");
            String totalAmount = params.get("total_amount");

            // 构建重定向URL的基础部分
            StringBuilder redirectUrl = new StringBuilder("http://localhost:8081/#/jingqu-service/payResult");
            redirectUrl.append("?orderNo=").append(URLEncoder.encode(orderNo, "UTF-8"));
            redirectUrl.append("&totalAmount=").append(URLEncoder.encode(totalAmount, "UTF-8"));

            if (signVerified) {
                // 支付成功
                redirectUrl.append("&status=success");
                log.info("支付成功，重定向到: {}", redirectUrl.toString());
            } else {
                // 验签失败
                redirectUrl.append("&status=fail");
                log.warn("验签失败，重定向到: {}", redirectUrl.toString());
            }

            response.sendRedirect(redirectUrl.toString());

        } catch (Exception e) {
            log.error("支付回调处理失败", e);
            // 发生异常时重定向到错误页面
            response.sendRedirect("http://localhost:8081/#/jingqu-service/payResult?status=error");
        }
    }
}
